import { service as axios, queryTrouble } from '@vimi/utils-api'
import { downloadByLink } from '@vimi/utils-tool'
import { getFileType } from '@/common/plugins/tools/file'

/*
 * Bolb导出文件格式
 * https://www.cnblogs.com/eedc/p/10069696.html
 */
export const mineTypeMap = new Map([
  // office
  ['doc', 'application/msword'],
  ['docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'],
  ['docm', 'application/vnd.ms-word.document.macroEnabled.12'],
  ['dotx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template'],
  ['dotm', 'application/vnd.ms-word.template.macroEnabled.12'],

  ['xls', 'application/vnd.ms-excel'],
  [
    'xlsx',
    'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  ],
  ['xlsm', 'application/vnd.ms-excel.sheet.macroEnabled.12'],
  ['xltx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template'],
  ['xltm', 'application/vnd.ms-excel.template.macroEnabled.12'],
  ['xlsb', 'application/vnd.ms-excel.sheet.binary.macroEnabled.12'],
  ['xlam', 'application/vnd.ms-excel.addin.macroEnabled.12'],

  ['ppt', 'application/vnd.ms-powerpoint'],
  ['pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
  ['pptm', 'application/vnd.ms-powerpoint.presentation.macroEnabled.12'],
  ['ppsx', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow'],
  ['ppsm', 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12'],
  ['potx', 'application/vnd.openxmlformats-officedocument.presentationml.template'],
  ['potm', 'application/vnd.ms-powerpoint.template.macroEnabled.12'],
  ['ppam', 'application/vnd.ms-powerpoint.addin.macroEnabled.12'],
  ['sldx', 'application/vnd.openxmlformats-officedocument.presentationml.slide'],
  ['sldm', 'application/vnd.ms-powerpoint.slide.macroEnabled.12'],

  ['one', 'application/msonenote'],
  ['onetoc2', 'application/msonenote'],
  ['onetmp', 'application/msonenote'],
  ['onepkg', 'application/msonenote'],
  ['thmx', 'application/vnd.ms-officetheme'],

  // pdf
  ['pdf', 'application/pdf'],

  // zip
  ['zip', 'application/zip'],
  ['rar', '.rar,application/x-rar-compressed'],
  ['gzip', 'application/gzip'],

  // image
  ['bmp', 'image/bmp'],
  ['gif', 'image/gif'],
  ['jpeg', 'image/jpeg'],
  ['jpg', 'image/jpeg'],
  ['png', 'image/png'],

  // video
  ['mpeg', 'video/mpeg'],
  ['mpg', 'video/mpeg'],
  ['avi', 'video/x-msvideo'],
  ['movie', 'video/x-sgi-movie'],
  ['mov', 'video/quicktime'],
  ['mp4', 'audio/mp4,video/mp4'],
  ['3gpp', 'audio/3gpp,video/3gpp'],
  ['wmv', 'video/x-ms-wmv'],

  // audio
  ['ac3', 'audio/ac3'],
  ['mid', 'audio/midi'],
  ['midi', 'audio/midi'],
  ['mp3', 'audio/mpeg'],
  ['rm', 'audio/x-pn-realaudio'],
  ['rpm', 'audio/x-pn-realaudio-plugin'],
  ['wav', 'audio/x-wav'],
  ['ogg', 'application/ogg,audio/ogg'],

  // web
  ['css', 'text/css'],
  ['html', 'text/html'],
  ['htm', 'text/html'],
  ['xsl', 'text/xml'],
  ['xml', 'text/xml'],
  ['js', 'application/x-javascript'],
  ['xhtml', 'application/xhtml+xml'],
  ['xht', 'application/xhtml+xml'],

  ['txt', 'text/plain'],
  ['csv', 'text/csv'],
  ['bin', 'application/octet-stream'],
  ['exe', 'application/octet-stream'],
  ['so', 'application/octet-stream'],
  ['dll', 'application/octet-stream'],
  ['ai', 'application/postscript'],
  ['dir', 'application/x-director'],
  ['swf', 'application/x-shockwave-flash'],
])

/**
 * 下载troubleQuery Stream
 * @param {*} param0 {}
 */
export const exportData = ({
  service,
  table,
  params = {},
  order,
  filename,
  onDownloadProgress,
}) => {
  params = {
    ...params,
    accept: 'application/octet-stream',
    filename: filename,
  }
  return exportUrl({
    url: `/api/${service}/${table}${queryTrouble(table, params, order)}`,
    type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    filename,
    onDownloadProgress,
  })
}

/**
 * 正常Url下载 Stream
 * @param {*} param0 {}
 */
export const exportUrl = ({
  url, // require
  filename, // require
  type,
  bookType,
  params = {},
  onDownloadProgress,
  responseType = 'blob',
}) =>
  axios
    .get(url, {
      params,
      responseType,
      onDownloadProgress,
      timeout: 0,
    })
    .then(res => {
      if (!res || !res.data) {
        throw new Error('empty response')
      }

      // 如果不定义type，则用bookType的定义
      if (!type) {
        if (!bookType) {
          bookType = getFileType(url)
        }
        type = mineTypeMap.get(bookType)
        // 如果文件名没有后缀，则用bookType作为后缀
        if (!/\.\w+$/.test(filename)) {
          filename += `.${bookType}`
        }
      }

      const downUrl = window.URL.createObjectURL(new Blob([res.data]), { type })
      downloadByLink({ url: downUrl, filename })
      window.URL.revokeObjectURL(downUrl)
    })
